package com.jkkc.lib.base.util

import android.os.Environment
import com.blankj.utilcode.util.LogUtils
import com.blankj.utilcode.util.ThreadUtils
import com.blankj.utilcode.util.ToastUtils
import com.jeremyliao.liveeventbus.LiveEventBus
import com.jkkc.lib.base.extend.BUS_INIT_WRITER_PATH
import java.io.BufferedWriter
import java.io.File
import java.io.FileWriter
import java.io.IOException
import java.util.*

/**
 * Author:LiXian
 * <p>
 * Desc:写入本地工具
 * Version:1.0
 * date 2023/2/7 15:13
 */
object WriterLocalUtils {

    private var mBackupPath: String = ""
    private var mLogPath: String = ""
    private var isSdCardExist: Boolean = false

    /**
     * 初始化写入本地路径
     *
     * @param backupPath 备份信息路径
     * @param logPath 操作信息路径
     */
    fun initWritePath(backupPath: String, logPath: String) {
        mBackupPath = backupPath
        mLogPath = logPath
        createFile(mBackupPath, ".txt")
        createFile(mLogPath, ".log")
    }

    /**
     * 创建文件夹和文件
     */
    private fun createFile(path: String, suffix: String): String {
        if (path.isEmpty()) {
            LiveEventBus.get(BUS_INIT_WRITER_PATH, String::class.java).post("")
            return ""
        }
        if (isSdCardExist || isSdCardExist()) {
            val filePath = path + File.separator + DateUtil.dateFormat(Date()) + suffix
            val file = File(filePath)
            if (!file.exists() && !file.isFile) {
                file.parentFile?.mkdirs()
                file.createNewFile()
            }
            return filePath
        } else {
            ToastUtils.showShort("不存在SD卡")
        }
        return ""
    }

    /**
     * 写入备份数据
     *
     * @param data 需要备份的数据
     * @param callback 写入结果回调
     */
    @JvmStatic
    @JvmOverloads
    fun writeBackupData(data: String, callback: ((Boolean) -> Unit)? = null) {
        val filePath = createFile(mBackupPath, ".txt")
        if (filePath.isEmpty()) return
        val mTask: ThreadUtils.SimpleTask<Boolean> = object : ThreadUtils.SimpleTask<Boolean>() {
            override fun doInBackground(): Boolean {
                var mBW: BufferedWriter? = null
                try {
                    // 第二个参数意义是说是否以append方式添加内容
                    mBW = BufferedWriter(FileWriter(filePath, true))
                    mBW.write(data)
                    mBW.write("\r\n\n")
                    mBW.flush()
                    mBW.close()
                } catch (e: Exception) {
                    if (mBW != null) {
                        try {
                            mBW.close()
                        } catch (ex: IOException) {
                            ex.printStackTrace()
                        }
                    }
                    return false
                }
                return true
            }

            override fun onSuccess(result: Boolean) {
                callback?.invoke(true)
                cancel()
            }

            override fun onFail(t: Throwable) {
                super.onFail(t)
                callback?.invoke(false)
                cancel()
            }
        }
        ThreadUtils.executeBySingle(mTask)
    }

    /**
     * 写入操作日志
     *
     * @param log 日志
     * @param callback 写入结果回调
     */
    @JvmStatic
    @JvmOverloads
    fun writeOperation(log: String, isAddTime: Boolean = true, callback: ((Boolean) -> Unit)? = null) {
        val filePath = createFile(mLogPath, ".log")
        if (filePath.isEmpty()) return
        val mTask: ThreadUtils.SimpleTask<Boolean> = object : ThreadUtils.SimpleTask<Boolean>() {
            override fun doInBackground(): Boolean {
                var mBW: BufferedWriter? = null
                try {
                    LogUtils.d("${DateUtil.long2Str(System.currentTimeMillis())},$log")
                    // 第二个参数意义是说是否以append方式添加内容
                    mBW = BufferedWriter(FileWriter(filePath, true))
                    if (isAddTime) {
                        mBW.write("${DateUtil.long2Str(System.currentTimeMillis())},$log")
                    } else {
                        mBW.write(log)
                    }
                    mBW.write("\r\n")
                    mBW.flush()
                    mBW.close()
                } catch (e: Exception) {
                    if (mBW != null) {
                        try {
                            mBW.close()
                        } catch (ex: IOException) {
                            ex.printStackTrace()
                        }
                    }
                    return false
                }
                return true
            }

            override fun onSuccess(result: Boolean) {
                callback?.invoke(true)
                cancel()
            }

            override fun onFail(t: Throwable) {
                super.onFail(t)
                callback?.invoke(false)
                cancel()
            }
        }
        ThreadUtils.executeBySingle(mTask)
    }

    /**
     * 判断SDCard是否存在 [当没有外挂SD卡时，内置ROM也被识别为存在sd卡]
     */
    private fun isSdCardExist(): Boolean {
        isSdCardExist = Environment.getExternalStorageState() == Environment.MEDIA_MOUNTED
        return isSdCardExist
    }
}